<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,user-scalable=no">
  <title>打地鼠</title>
  <style>
    *{
      margin: 0;padding: 0;
    }
  </style>
</head>
<body>
  <div id="game" class="game"></div>
  <script src="//cdn.bootcss.com/phaser/2.6.2/phaser.min.js"></script>
  <script>

      var width = 640;
      var height = (width / window.innerWidth) * window.innerHeight;
      // var height = 750/window.innerWidth*window.innerHeight
      // 创建游戏实例
      // new Game(width, height, renderer, parent, state, transparent, antialias, physicsConfig)
      var game = new Phaser.Game(width, height, Phaser.CANVAS, "game");

      game.States = {};
      game.States.boot = function () {
        this.preload = function () {};
        this.create = function () {
          game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
          game.state.start("preload");
        };
      };
      game.States.preload = function () {
        this.preload = function () {
          // 设置背景为黑色
          game.stage.backgroundColor = "#000000";
          // 加载游戏资源
          game.load.crossOrigin = "anonymous";

          game.load.image("gameBg", "./images/gameBg.jpg");
          game.load.image(
            "hamster1",
            "./images/hamster1.png"
          );
          game.load.image(
            "hamster2",
            "./images/hamster2.png"
          );
          game.load.image("hole1", "./images/hole1.png");
          game.load.image("hole2", "./images/hole2.png");

          // 添加进度文字
          var progressText = game.add.text(
            game.world.centerX,
            game.world.centerY,
            "0%",
            {
              fontSize: "32px",
              fill: "#ffffff",
            }
          );
          //设置锚点
          progressText.anchor.setTo(0.5, 0.5);
          // 监听加载完一个文件的事件
          game.load.onFileComplete.add(function (progress) {
            progressText.text = progress + "%";
          });
          //监听加载完毕事件
          game.load.onLoadComplete.add(onLoad);

          function onLoad() {
            game.state.start("start");
          }
        };
        this.create = function () {
          // game.state.start("start");
        };
      };
      //开始页面
      game.States.main = function () {
        this.create = function () {
          game.state.start("start");
        };
      };
      //游戏开始
      game.States.start = function () {
        let position = [
          {
            x: 130,
            y: 450,
          },
          {
            x: 320,
            y: 450,
          },
          {
            x: 500,
            y: 450,
          },
          {
            x: 130,
            y: 630,
          },
          {
            x: 320,
            y: 630,
          },
          {
            x: 500,
            y: 630,
          },
          {
            x: 130,
            y: 800,
          },
          {
            x: 320,
            y: 800,
          },
          {
            x: 500,
            y: 800,
          },
        ];
        function autoX(w) {
          return (width / 640) * w;
        }
        this.create = function () {
          // 背景
          this.bg = game.add.tileSprite(
            0,
            0,
            game.world.width,
            (game.world.width / game.cache.getImage("gameBg").width) *
              game.cache.getImage("gameBg").height,
            "gameBg"
          );
          for (let i = 0; i < position.length; i++) {
            this.hole1 = this.add.sprite(
              autoX(position[i].x),
              autoX(position[i].y + 20),
              "hole1"
            );
            this.hole1.anchor.setTo(0.5, 0.5);
            this.hole1.width = 160;

            this.hole1.height =
              (this.hole1.width / game.cache.getImage("hole1").width) *
              game.cache.getImage("hole1").height;
              // console.log(this.hole1);
          }
          for (let i = 0; i < position.length; i++) {
            this.hole2 = this.add.sprite(
              autoX(position[i].x),
              autoX(position[i].y + 70),
              "hole2"
            );
            this.hole2.anchor.setTo(0.5, 0.5);
            this.hole2.width = autoX(160);
            this.hole2.height =
              (this.hole2.width / game.cache.getImage("hole2").width) *
              game.cache.getImage("hole2").height;
          }
          

          this.score = 0;
          this.time = 120;
          //添加分数
          this.scoreText = game.add.text(20, 40, "分数：0", {
            fontSize: "32px",
            fontWeight: "bold",
            fill: "#fff",
          });
          this.scoreText.anchor.setTo(0, 0.5);
          //时间
          this.timeText = game.add.text(
            game.world.centerX,
            40,
            tick2(this.time),
            {
              fontSize: "32px",
              fontWeight: "bold",
              fill: "#fff",
            }
          );
          this.timeText.anchor.setTo(0.5, 0.5);
          this.timer = game.time.events.loop(Phaser.Timer.SECOND, tick, this);

          function tick() {
            this.time--;
            var minutes = Math.floor(this.time / 60);
            var seconds = this.time - minutes * 60;
            var timeString = addZeros(minutes) + ":" + addZeros(seconds);
            this.timeText.text = timeString;
            if (this.time == 0) {
              game.time.events.remove(this.timer);
              game.paused = true;
            }
          }
          function tick2(time) {
            var minutes = Math.floor(time / 60);
            var seconds = time - minutes * 60;
            var timeString = addZeros(minutes) + ":" + addZeros(seconds);
            return timeString;
          }

          function addZeros(num) {
            if (num < 10) {
              num = "0" + num;
            }
            return num;
          }
          this.speed = 1000; // 地鼠出现时长，单位为毫秒，初始数值
          this.orderIndex = 0; // 地鼠出现位置数组下标初始化
          this.isShow = false; // 地鼠当前是否出现初始化
          this.showOrder = []; // 小地鼠出现位置数组
          this.showOrder[0] = Math.floor(Math.random() * 9);
          
          for (var i = 1; i < 2; ) {
            this.showOrder[1] = Math.floor(Math.random() * 9);
            if (this.showOrder[1] != this.showOrder[0]) i++;
          }
          //生成一串每3个都不相同的数字。避免多个地鼠在同一个洞里
          for (var i = 2; i < this.time * 3; ) {
            this.showOrder[i] = Math.floor(Math.random() * 9);
            if (
              this.showOrder[i] != this.showOrder[i - 1] &&
              this.showOrder[i] != this.showOrder[i - 2]
            )
              i++;
          }
          // console.log(this.showOrder);
        };
        //地鼠出现展示的最大时长和最小时长
        let min = 300;
        let max = 500;
        // 更新函数
        this.update = function () {
          if (!this.isShow) {
            // console.log("地鼠出现！");
            this.isShow = true;
            let hole = this.showOrder[this.orderIndex]; // 地鼠随机位置获取
            //tileSprite可以裁剪！！！
            let hamster = this.add.tileSprite(
              autoX(position[hole].x),
              autoX(position[hole].y + 100),
              150,
              130,
              "hamster1"
            );
            hamster.anchor.setTo(0.5, 0.5);
            hamster.height = 0;
            hamster.width = 150;
            //给生成的地鼠设置层级
            game.world.setChildIndex(hamster, 10);
            let show = game.add.tween(hamster).to(
              {
                height: 130,
                y: hamster.y - 100,
              },
              game.rnd.between(min, max),
              Phaser.Easing.Linear.None,
              true,
              0,
              0,
              false
            );
            
            hamster.click = true;
            let that = this;
            let hide = null;
            let time2 = game.rnd.between(this.speed, this.speed + 500);
            setTimeout(() => {
              that.orderIndex++;
              that.isShow = false;
              if (this.speed > 500) {
                this.speed -= 30;
              }

              setTimeout(() => {
                // 地鼠消失
                if (!hamster.click) return;
                hide = game.add.tween(hamster).to(
                  {
                    y: hamster.y + 100,
                    height: 0,
                  },
                  game.rnd.between(min, max),
                  Phaser.Easing.Linear.None,
                  true,
                  0,
                  0,
                  false
                );

                // console.log("地鼠消失~");
              }, time2 - game.rnd.between(0, time2));
            }, game.rnd.between(time2 - 300, time2));

            hamster.inputEnabled = true;

            hamster.events.onInputDown.add(() => {
              if (!hamster.click) return;
              // console.log("打");
              this.score++;
              this.scoreText.text = "分数：" + this.score;
              if (hide) hide.pause();
              hamster.click = false;
              hamster.loadTexture("hamster2");
              setTimeout(() => {
                hamster.kill();
              }, 1000);
            });
          }
        };
      };
      game.state.add("boot", game.States.boot);
      game.state.add("preload", game.States.preload);
      game.state.add("main", game.States.main);
      game.state.add("start", game.States.start);
      game.state.add("over", game.States.over);
      game.state.start("boot");
  </script>
</body>
</html>